import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.core.TransactionalMap;
import com.hazelcast.transaction.TransactionContext;

import util.NearCacheTest;

/**
 * transaction map 开始后，读取相关要素的线程将被阻塞
 * 
 * @author wxu
 *
 */
public class TransactionalNearCache {

	private static final Logger logger = LoggerFactory.getLogger(TransactionalNearCache.class);

	static Runnable tx = new Runnable() {
		@Override
		public void run() {

			try {
				logger.info("start transaction...");
				TransactionContext txCxt = hz.newTransactionContext();
				txCxt.beginTransaction();
				TransactionalMap<Object, Object> map = txCxt.getMap(NearCacheTest.MAP);

				try {
					logger.info("before put map(1)");
					Thread.sleep(300);
					map.put("1", "1"); // reader1 is blocked
					logger.info("after put map(1)");
					Thread.sleep(500);
					map.put("2", "2"); // reader2 is blocked
					logger.info("after put map(2)");
					Thread.sleep(500);
					txCxt.commitTransaction();
					logger.info("transaction committed");
				} catch (RuntimeException t) {
					txCxt.rollbackTransaction();
					throw t;
				}

				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
//				Hazelcast.shutdownAll();
				logger.info("system exit.");
				System.exit(0);
			}

		}
	};

	private static HazelcastInstance hz;

	public static void main(String[] args) throws Exception {

		hz = Hazelcast.newHazelcastInstance();
		IMap<String, String> testmap = hz.getMap(NearCacheTest.MAP);
		testmap.set("3", "3");

		new NearCacheTest();

		Thread.sleep(3000);
		new Thread(tx, "transaction").start();

		// Hazelcast.shutdownAll();
		// System.exit(0);
	}
}
